package json.scheme;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URL;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jsonschema2pojo.SchemaMapper;

import com.sun.codemodel.JCodeModel;

/**
 * 
 * @author 365
 *
 */
public class JsonSchemeServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String json = request.getParameter("schema");
		// 包名
		String packageName = request.getParameter("targetpackage");
		// 类名
		String className = request.getParameter("classname");
		// 文件保存的路径
		String path = request.getServletContext()
				.getRealPath("/WEB-INF/upload");

		if (checkInputInfo(response, packageName, className)) {
			// response.setContentType("text/xml");
			response.setCharacterEncoding("utf-8");
			// 文件
			File file = new File(path, className + ".json");
			PrintWriter writer = new PrintWriter(file);
			writer.print(json);
			writer.close();
			// 将JSON格式转化为Java类
			try {
				JCodeModel codeModel = new JCodeModel();
				URL url = file.toURI().toURL();
				new SchemaMapper().generate(codeModel, className, packageName,
						url);
				codeModel.build(new File(path));
				// 将转换好的Java类在前台显示
				String javaPath = path + "/" + packageName.replace(".", "/")
						+ "/";
				File javaFile = new File(javaPath, className + ".java");
				BufferedReader br = new BufferedReader(new FileReader(javaFile));
				String content = "";
				String line = "";
				while ((line = br.readLine()) != null) {
					content = content + "\n" + line;
				}
				br.close();
				//删除Java文件,防止在创建的时候导致调用了原来的文件
				javaFile.delete();
				response.getWriter().write(content);
			} catch (Exception e) {
				response.getWriter().write(json);
			}

		} else {
			return;
		}

	}

	private boolean checkInputInfo(HttpServletResponse response,
			String packageName, String className) throws IOException {
		if (packageName.isEmpty()) {
			response.setContentType("text/xml; charset=utf-8");
			response.getWriter().write("包名不能为空");
			return false;
		} else if (className.isEmpty()) {
			response.setContentType("text/xml; charset=utf-8");
			response.getWriter().write("类名不能为空");
			return false;
		}
		return true;
	}

	public boolean isEmpty(String name) {
		if (name == null || name.length() == 0) {
			return true;
		}
		return false;
	}

}
